#include <time.h>
#include <cstdio>
#include <cstdlib>

#include <dice/dice.h>

void dice_init(){
    srand(time(NULL));
}

dice::dice():   result( 0 ),
                throwval( 0 ),
                canReroll( false )
{}

dice::dice(unsigned int val,bool rer):  result( 0 ),
                                        throwval( val ),
                                        canReroll( rer )
{
    unsigned int res;
    do{
        result += res = 1 + (unsigned int)(((float)rand()/(float)RAND_MAX)*((float)val));
        #if ECHO
            printf("Throw (%u): %u -> %u\n",throwval,res,result);
        #endif
    }while( res == val && canReroll );
}

dice::~dice(){

}

dice dice::roll(unsigned int val){
    return dice(val);
}

void dice::reroll(){
    if( !throwval ) return;
    unsigned int res;
    result = 0;
    do{
        result += res = 1 + (unsigned int)(((float)rand()/(float)RAND_MAX)*((float)throwval));
        #if ECHO
            printf("Throw (%u): %u -> %u\n",throwval,res,result);
        #endif
    }while( res == throwval && canReroll );
}

unsigned int dice::getResult(){
    return result;
}

void dice::setResult(unsigned int val){
    result = val;
}

dice dice::operator+(int value){
    result += (unsigned int)value;
    dice e;
    e.setResult( result );
    return e;
}

dice dice::operator+(dice d){
    result += d.getResult();
    dice e;
    e = result;
    return e;
}

dice dice::operator=(int value){
    result = (unsigned int)value;
    return dice();
}

dice::operator unsigned int(){
    return result;
}

dice operator*(int throws, dice d){
    if( throws == 0 ) return dice();
    unsigned int res = d;
    throws--;
    while( throws ){
        d.reroll();
        res += (unsigned int)d;
        throws--;
    }
    d = res;
    return d;
}

dice operator*(dice d,int val){
    d = ((int)d)*val;
    return d;
}
